package org.duiduo.handler;

import lombok.extern.slf4j.Slf4j;
import org.duiduo.exception.CustomException;
import org.duiduo.api.response.Result;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常处理
 *
 * @author liangze
 */
@Slf4j
@ControllerAdvice(basePackages = "org.duiduo.controller")
public class GlobalExceptionHandler {

    // 统一异常处理@ExceptionHandler,主要用于Exception
    @ExceptionHandler(CustomException.class)
    @ResponseBody // 返回json串
    public Result<?> customer(CustomException e) {
        log.error("错误码code:{},错误信息msg:{}", e.getCode(), e.getMsg());
        return Result.error(e.getCode(), e.getMsg());
    }

    // 统一异常处理@ExceptionHandler,主要用于Exception
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody // 返回json串
    public Result<?> illegalArgumentCustomer(HttpServletRequest request, Exception e) {
        log.error("错误信息msg:{}", e.getMessage());
        return Result.error("-1", e.getMessage());
    }

    // 统一异常处理@ExceptionHandler,主要用于Exception
    @ExceptionHandler(Exception.class)
    @ResponseBody // 返回json串
    public Result<?> customer(HttpServletRequest request, Exception e) {
        String message = "";
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ve = (MethodArgumentNotValidException) e;
            message =  ve.getBindingResult().getFieldError().getDefaultMessage();
            log.error("错误信息msg:{}", message);
            return Result.error("-1", message);
        } else {
            log.error("系统异常:", e);
            return Result.error("-1", "系统异常");
        }
    }
}
